package spring.cloud.tasks.tasks_manager.tasks_manager.listener;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;

@Slf4j
@Setter
@Getter
public class TaskConfigListener extends TreeCacheListener {

    private String taskId;
    private String enabledPath;
    private String forceShardPath;
    private AllotTaskItemService allotTaskItemService;


    public TaskConfigListener(String taskId, AllotTaskItemService allotTaskService) {
        this.taskId = taskId;
        this.enabledPath = Node.getJobConfigEnableNodePath(taskId);
        this.forceShardPath = Node.getTaskConfigForceShardNodePath(taskId);
        this.allotTaskItemService = allotTaskService;

    }

    @Override
    public void childEvent(Type type, String path, String nodeData) throws Exception {
        if (isTaskEnabledPath(type, path)) {
            if (Boolean.parseBoolean(nodeData)) {
                allotTaskItemService.taskEnableAllotTask(taskId);
            } else {
                allotTaskItemService.taskDisableAllotTask(taskId);
            }
        } else if (isForceReAllotdJob(type, path)) {
            allotTaskItemService.taskExecuteForceTaskItemAllotTask(taskId);
        }
    }

    private boolean isTaskEnabledPath(TreeCacheEvent.Type type, String path) {
        return type == TreeCacheEvent.Type.NODE_UPDATED && path.equals(enabledPath);
    }

    private boolean isForceReAllotdJob(TreeCacheEvent.Type type, String path) {
        return type == TreeCacheEvent.Type.NODE_ADDED && path.equals(forceShardPath);
    }
}
